<template>
  <div class="main">
    <el-button type="primary" @click="dialogVisible = true">证件识别</el-button>
    <el-dialog
      title="证件识别(批量上传总文件大小不超过15M)"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
      :destroy-on-close="true"
    >
      <div class="dialog-content">
        <div class="btn_ocr">
          <div class="text_while_ocr">
            <span>共计:{{this.ocrImgList.length}}张</span>
            <span>识别完成:{{ocrSuccess}}张</span>
            <span>识别失败:{{ocrFail}}张</span>
            <span>正在识别:{{ocrOngoing}}张</span>
          </div>
          <div class="btns_ocr">
            <el-button size="small" type="primary" @click="beforeImagesUpload">身份证识别</el-button>
            <input type="file" style="display:none" id="file" multiple />
            <el-button style="margin-left:15px" size="small" @click="clear">清空</el-button>
          </div>
        </div>
        <div class="ocr_list">
          <div class="ocr_img_box" v-for="(item,index) in ocrImgList" :key="item.id">
            <span @click="closeOcr(item,index)" class="idCard_box_close_x">
              <img src="../assets/logo.png" alt />
            </span>
            <img class="ocr_img" :src="item.url" alt />
            <div class="ocr_info">
              <div class="ocr_info_data" v-if="item.result_code=='0000'">
                <p>
                  姓名：
                  <span>{{item.result.name}}</span>
                </p>
                <p>
                  证件类型：
                  <span>{{item.result.type==1?'身份证':'护照'}}</span>
                </p>
                <p>
                  证件号：
                  <span>{{item.result.card}}</span>
                </p>
                <p>
                  生日：
                  <span>{{item.result.birthday}}</span>
                </p>
              </div>
              <div class="ocr_info_erroe" v-if="item.result_code=='0001'">
                <span>证件识别失败!</span>
              </div>
            </div>
            <div v-if="item.closeFlag" class="loading_column">
              <div class="element"></div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="upDataOcr">上传数据</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Axios from "axios";
export default {
  data() {
    return {
      dialogVisible: true,
      ocrImgList: [],
      fileList: [],
      ocrSuccess: 0,
      ocrFail: 0,
      ocrOngoing: 0
    };
  },
  methods: {
    handleClose(done) {
      done();
      this.ocrImgList = [];
      this.ocrSuccess = 0;
      this.ocrFail = 0;
      this.ocrOngoing = 0;
    },
    async beforeImagesUpload() {
      document.querySelector("#file").value = "";
      let that = this; //改变作用域
      let promise = new Promise(function(resolve, reject) {
        let fileList = [];
        let file = document.querySelector("#file");
        file.click();
        let sum = 0;
        file.onchange = function(event) {
          let files = "";
          files = event.target.files;
          that.ocrOngoing = files.length;
          for (let i = 0; i < files.length; i++) {
            let file = files[i];
            const isJPEG = file.type === "image/jpeg";
            const isGPG = file.type === "image/jpg";
            const isPNG = file.type === "image/png";
            if (!isPNG && !isJPEG && !isGPG) {
              reject("type");
            }
            let url = URL.createObjectURL(file);
            let filename = file.name;
            that.ocrImgList.forEach((items, index) => {
              if (items.filename == filename) {
                reject("name");
              }
            });

            let closeFlag = false;
            //随机数8位
            let id = Math.random().toString(36).substr(2, 8);
            const isLt2M = file.size / 1024 / 1024 < 1.5;
            if (!isLt2M) {
              reject("size_1.5");
            }
            sum += file.size;
            if (sum / 1024 / 1024 > 15) {
              reject("size_15");
            }
            fileList.push({
              file: file,
              id: id,
              filename: filename,
              url: url,
              closeFlag: closeFlag
            });
          }
          resolve(fileList); //通过resolve将fileList抛出，在后续使用
        };
      }).then(function(value) {
        //状态为resolved时调用，这里的value就是resolve抛出的数据
        // console.log(value, "then"); //成功打印
        that.ocrImgList = that.ocrImgList.concat(value); //储存
        that.upload(that.ocrImgList); //正式上传
      })
      .catch(error => {
        console.log( that.ocrImgList);
        console.log(error);
        if (error == "size_1.5") {
          that.$message.error("单张照片最大1.5MB！");
        } else if (error == "size_15") {
          that.$message.error("上传的图片总体大小不能超过15MB!");
        } else if (error == "type") {
          that.$message.error("上传识别图片仅支持JPG、GIF、PNG、JPEG!");
        } else if (error == "name") {
          that.$message.error("上传的图片名称不能重复!");
        }
      });
      // promise.then(
      //   // 成功回调
      //   success => {
      //     //状态为resolved时调用，这里的value就是resolve抛出的数据
      //     console.log(value, "then"); //成功打印
      //     that.ocrImgList = that.ocrImgList.concat(value); //储存
      //     that.upload(that.ocrImgList); //正式上传
      //   },
      //   // 失败回调
      //   error => {
      //      console.log(error);
      //     if (error == "size_1.5") {
      //       that.$message.error("单张照片最大1.5MB！");
      //     } else if (error == "size_15") {
      //       that.$message.error("上传的图片总体大小不能超过15MB!");
      //     } else if (error == "type") {
      //       that.$message.error("上传识别图片仅支持JPG、GIF、PNG、JPEG!");
      //     } else if (error == "name") {
      //       that.$message.error("上传的图片名称不能重复!");
      //     }
      //   }
      // );
    },
    upload(value) {
      let x = 0;
      return;
      value.map((item, index) => {
        if (item.result_code) {
          return;
        }
        item.closeFlag = true;
        let formData = new FormData();
        formData.append("file", item.file);
        Axios.post(
          process.env.VUE_APP_INSURANCE_API +
            "noCarPartner/JSLYJF/recognizeIdcard",
          formData
        ).then(res => {
          x = index;
          let OCROBJ = this.ocrImgList[x];
          this.ocrImgList[x].closeFlag = false;
          this.ocrImgList[x] = { ...OCROBJ, ...res.data };
          let num = 0;
          let unnum = 0;
          this.ocrImgList.forEach((item, index) => {
            if (item.result_code == "0000") {
              num++;
            }
            if (item.result_code == "0001") {
              unnum++;
            }
          });
          this.ocrSuccess = num;
          this.ocrFail = unnum;
          this.ocrOngoing = this.ocrImgList.length - num - unnum;
        });
      });
    },
    //清空按钮
    clear() {
      this.ocrImgList = [];
    },
    //单体删除
    closeOcr(item, index) {
      console.log(item);
      if (item.result_code == "0000") {
        this.$confirm("确认删除识别完成的数据？, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.ocrImgList.splice(index, 1);
            let num = 0;
            this.ocrImgList.forEach((item, index) => {
              if (item.result_code == "0000") {
                num++;
              }
            });
            this.ocrSuccess = num;
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      } else {
        this.ocrImgList.splice(index, 1);
        let unnum = 0;
        this.ocrImgList.forEach((item, index) => {
          if (item.result_code == "0001") {
            unnum++;
          }
        });
        this.ocrFail = unnum;
      }
    },
    //传递数据
    upDataOcr() {
      let arr = [];
      this.ocrImgList.map((item, index) => {
        if (item.result_code !== "0000") {
          this.option ? this.option.close() : "";
          this.option = this.$message({
            type: "error",
            message: "有未识别成功的图片，请删除后再上传!"
          });
          return;
        }
        if (item.result_code == "0000") {
          arr.push(item.result);
        }
      });
    }
  }
};
</script>


<style lang="less"  scoped>
.main {
  width: 100%;
  height: 100vh;
  background: #fff;
  padding: 100px;
  box-sizing: border-box;
}
::v-deep .el-dialog__body {
  padding: 0;
}
::v-deep .el-dialog__footer {
  text-align: center;
}
::v-deep .el-dialog__headerbtn {
  display: block;
}
::v-deep .el-dialog__header {
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  .el-dialog__title {
    font-size: 16px;
    font-weight: 600;
  }
}

.dialog-content {
  width: 100%;
  height: 650px;
  .btn_ocr {
    display: flex;
    border-bottom: 1px solid #e8e8e8;
    padding: 10px;
    box-sizing: border-box;
    .text_while_ocr {
      display: flex;
      flex-wrap: wrap;
      flex: 1;
      span {
        display: block;
        width: 100px;
        border: 1px solid #8cd4ff;
        color: #8cd4ff;
        background: #f5fbff;
        text-align: center;
        height: 30px;
        line-height: 30px;
      }
      span:nth-child(2) {
        border-left: none;
        border-right: none;
      }
      span:nth-child(3) {
        border-right: none;
      }
      //屏幕小于750px
      @media screen and (max-width: 1400px) {
        span {
          border: 1px solid #8cd4ff;
        }
        span:nth-child(2) {
          border: 1px solid #8cd4ff;
        }
        span:nth-child(3) {
          border: 1px solid #8cd4ff;
        }
      }
    }
    .btns_ocr {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
  .ocr_list {
    width: 100%;
    height: 90%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    padding: 0 15px;
    padding-top: 20px;
    box-sizing: border-box;
    overflow: auto;
    .ocr_img_box {
      width: 200px;
      height: 220px;
      border: 1px solid #ccc;
      box-sizing: border-box;
      margin-left: 10px;
      margin-bottom: 10px;
      position: relative;
      .idCard_box_close_x {
        position: absolute;
        right: -10px;
        top: -15px;
        z-index: 1000;
      }
      .ocr_img {
        width: 100%;
        height: 120px;
        padding: 2px 5px;
        box-sizing: border-box;
        object-fit: contain;
      }
      .ocr_info {
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        .ocr_info_data {
          font-size: 12px;
          color: #333;
          p {
            margin-bottom: 4px;
          }
          span {
            font-weight: 600;
          }
        }
        .ocr_info_erroe {
          text-align: center;
          font-size: 16px;
          color: red;
        }
      }

      .loading_column {
        width: 100%;
        @keyframes up {
          from {
            width: 0;
            /* 动画开始时元素的宽度 */
          }

          to {
            width: 100%;
            /* 动画结束时元素的宽度 */
          }
        }

        /* 应用动画到具体的元素 */
        .element {
          height: 8px;
          background-color: #8cd4ff;
          animation: up 10s ease forwards;
          transform: translate(0, -5px);
          /* 'up' 是动画名，5s 是动画时长，ease 是动画速度曲线，forwards 是动画完成后保持最后状态 */
        }
      }
    }
    // .ocr_img_box_close_active{
    //   position: absolute;
    //   width: 100%;
    //   height: 100%;
    //   background-color: rgba(34, 34, 34, .5);
    // }
  }
}
</style>